package icursoft.educationms;

import android.app.Activity;
import android.app.Application;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.store.PersistentCookieStore;

import org.litepal.LitePalApplication;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

/**
 * Created by wang on 2017/4/19.
 */

public class EducationMSApplication extends LitePalApplication {
    private final static String TAG = EducationMSApplication.class.getSimpleName();
    private static EducationMSApplication sInstance;
    public final static Gson GSON = new Gson();
    private List<Activity> activitys = new ArrayList<Activity>();

    public EducationMSApplication() {
        this.sInstance = this;
    }
    public static EducationMSApplication getInstance() {
        if(sInstance==null){
            sInstance = new EducationMSApplication();
        }
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initOkGo();
    }
    private void initOkGo() {
        OkGo.init(this);
        try {
            OkGo.getInstance()
                    // 最后的true表示是否打印okgo的内部异常，一般打开方便调试错误
                    .debug("OkGo" )
                    //设置默认的超时时间 默认60s
                    .setConnectTimeout(OkGo.DEFAULT_MILLISECONDS) //全局的连接超时设置
                    .setReadTimeOut(OkGo.DEFAULT_MILLISECONDS)     //全局的读取超时时间
                    .setWriteTimeOut(OkGo.DEFAULT_MILLISECONDS)    //全局的写入超时时间

                    //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/
                    .setCacheMode(CacheMode.NO_CACHE)
                    .setCookieStore(new PersistentCookieStore())        //cookie持久化存储，如果cookie不过期，则一直有效

                    //可以设置https的证书,以下几种方案根据需要自己设置
                    .setCertificates()                                  //方法一：信任所有证书,不安全有风险
            ;
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    /**
     * 添加activity至list
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        String className = activity.getClass().getName();
        for (Activity at : activitys) {
            if (className.equals(at.getClass().getName())) {
                activitys.remove(at);
                break;
            }
        }
        activitys.add(activity);
    }

    public void deleteActivity(Activity activity) {
        String className = activity.getClass().getName();
        for (Activity at : activitys) {
            if (className.equals(at.getClass().getName())) {
                activitys.remove(at);
                break;
            }
        }
    }
    /**
     * 逐个关闭list中的activity
     */
    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        for (Activity activity : activitys) {
            activity.finish();
        }
    }

}
